﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;



using Autodesk.AutoCAD.DatabaseServices;// (Database, DBPoint, Line, Spline) 
using Autodesk.AutoCAD.ApplicationServices;// (Application, Document) 
using Autodesk.AutoCAD.EditorInput;//(Editor, PromptXOptions, PromptXResult)
//EXCEL 表格引用
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;   //
using NPOI.XSSF.UserModel;
using System.IO;
using System.Runtime.InteropServices;  //应用[DllImport("user32.dll")]需要
using Application = Autodesk.AutoCAD.ApplicationServices.Application;


namespace ExportTextPosition
{
    public partial class Form1 : Form
    {

        //初始化  窗口焦点切换功能
        [DllImport("user32.dll", EntryPoint = "SetFocus")]
        public static extern int SetFocus(IntPtr hWnd);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> lstAddStr = new List<string>();   //放置第一个文本内容
            List<string> lstAddStr1 = new List<string>();  //放置第二个文本内容
            List<string> lstAddStrX = new List<string>();  //放置第一个文本内容X坐标
            List<string> lstAddStrY = new List<string>();  //放置第一个文本内容Y坐标
            List<string> lstAddStrX1 = new List<string>(); //放置第二个文本内容X坐标
            List<string> lstAddStrY1 = new List<string>(); //放置第二个文本内容Y坐标

            Database db = HostApplicationServices.WorkingDatabase;
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;


            using (DocumentLock acLckDoc = doc.LockDocument())
            {
                //框选获取文字 选择集知识点
                TypedValue[] typedvalue = new TypedValue[7];
                typedvalue.SetValue(new TypedValue((int)DxfCode.Operator, "<and"), 0);
                typedvalue.SetValue(new TypedValue(0, "*TEXT"), 1);
                typedvalue.SetValue(new TypedValue((int)DxfCode.Operator, "<or"), 2);
                typedvalue.SetValue(new TypedValue((int)DxfCode.Text, "*52-V007*"), 3);      
                typedvalue.SetValue(new TypedValue((int)DxfCode.Text, "*布置图*"), 4);
                typedvalue.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), 5);
                typedvalue.SetValue(new TypedValue((int)DxfCode.Operator, "and>"), 6);

                // 将过滤条件赋值给SelectionFilter对象
                SelectionFilter selFtr = new SelectionFilter(typedvalue);

                //请求在图形区域选择对象
                PromptSelectionResult psr = ed.GetSelection(selFtr);
                

                if (psr.Status == PromptStatus.OK)
                {
                    SelectionSet sSet = psr.Value;
                    Application.ShowAlertDialog("一共选取的对象数为:" + sSet.Count.ToString());
                    foreach (SelectedObject acSSObj in sSet)
                    {
                        // 确认返回的是合法的SelectedObject对象  
                        if (acSSObj != null) //
                        {
                            using (Transaction trans = db.TransactionManager.StartTransaction())
                            {
                                DBText myent = trans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as DBText;
                                if (myent.TextString.Contains("52-"))
                                {
                                    lstAddStr.Add(myent.TextString);
                                    lstAddStrX.Add(myent.Position.X.ToString());
                                    lstAddStrY.Add(myent.Position.Y.ToString());
                                }
                                else if (myent.TextString.Contains("布置图"))
                                {
                                    lstAddStr1.Add(myent.TextString);
                                    lstAddStrX1.Add(myent.Position.X.ToString());
                                    lstAddStrY1.Add(myent.Position.Y.ToString());
                                }
                            }
                        }                            
                    }
                }

                else
                {
                    Application.ShowAlertDialog("选取对象数目: 0");
                }

                //数据接下来输出到EXCEL表格
                IWorkbook wk = null;  //新建IWorkbook对象

                string localFilePath = "D:\\TEST.xlsx"; //指定路径

                // 调用一个系统自带的保存文件对话框 写一个EXCEL
                SaveFileDialog saveFileDialog = new SaveFileDialog();   //新建winform自带保存文件对话框对象
                saveFileDialog.Filter = "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";  //过滤只能存储的对象
                DialogResult result = saveFileDialog.ShowDialog();     //显示对话框
                localFilePath = saveFileDialog.FileName.ToString();
                //07版之前和之后创建方式不一样
                if (localFilePath.IndexOf(".xlsx") > 0) // 2007版本 
                {
                    wk = new XSSFWorkbook();   //创建表格对象07版之后
                }
                else if (localFilePath.IndexOf(".xls") > 0) // 创建表格对象 2003版本
                {
                    wk = new HSSFWorkbook();  //03版
                }
                //创建工作簿
                ISheet tb = wk.CreateSheet("输出的文本");

                for (int i = 0; i < lstAddStr.Count; i++)
                {
                    ICell cell0 = tb.CreateRow(i).CreateCell(0);  //单元格对象 第i行第1列  
                    ICell cell1 = tb.CreateRow(i).CreateCell(1);  //单元格对象 第i行第2列  
                    ICell cell2 = tb.CreateRow(i).CreateCell(2);  //单元格对象 第i行第3列  
                    ICell cell3 = tb.CreateRow(i).CreateCell(3);  //单元格对象 第i行第4列  
                    ICell cell4 = tb.CreateRow(i).CreateCell(4);  //单元格对象 第i行第5列 
                    ICell cell5 = tb.CreateRow(i).CreateCell(5);  //单元格对象 第i行第6列 


                    //循环往单元格赋值
                    cell0.SetCellValue(lstAddStr[i]);     //图号字符串
                    cell1.SetCellValue(lstAddStrX[i]);    //图号X坐标
                    cell2.SetCellValue(lstAddStrY[i]);    //图号Y坐标
                    cell3.SetCellValue(lstAddStr1[i]);    //图名字符串
                    cell4.SetCellValue(lstAddStrX1[i]);   //图名X坐标
                    cell5.SetCellValue(lstAddStrY1[i]);   //图名Y坐标

                }
                

                //创建文件
                using (FileStream fs = File.OpenWrite(localFilePath)) //打开一个xls文件，如果没有则自行创建，如果存在myxls.xls文件则在创建是不要打开该文件！
                {
                    wk.Write(fs);   //文件IO 创建EXCEL
                    MessageBox.Show("已输出坐标到Excel！");
                    fs.Close();
                }


            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
